<?php

namespace Home\Controller;
use Think\Server;
use Think\Db;

header('content-type:text/html;charset=utf-8');
class WorkermanlonghuController extends Server {

	protected $socket = 'websocket://0.0.0.0:15101';

    /*添加定时器
     *监控连接状态
     * */
    public function onWorkerStart(){
        $msg_data = array();
        $auth = auth_check(C('auth_code'),C('siteurl'));
        if (!$auth) {
            echo "未授权或授权已过期";exit;
        }

        /*结算*/
        $time_interval = 1;//定时一秒 即每秒触发一次
        \Workerman\Lib\Timer::add($time_interval, function(){

            //机器人
            $hundred = M('hundred')->where("type=1")->order("id desc")->find();
            if ($hundred['status']==9){
                $robot_t= robot_pinlv();//机器人频率
                $robot2=F('longhu');
                if ($robot2&&$robot2>0){
                    F('longhu',$robot2-1);
                }else {
                    if ($robot2 == 0) {//机器人启动
                        //机器人
                        $mess = $this->robot_message();
                        $robot = $this->robot();
                        $new_message = array(
                            'type' => 'say',
                            'head_img_url'=>'/Uploads'.$robot[0]['headimgurl'],
                            'from_client_name' => $robot[0]['nickname'],
                            'content'=>$mess,
                            'time'=>date('H:i:s')
                        );
                        foreach ($this->worker->uidConnections as $con) {
                            $con -> send(json_encode($new_message));
                        }
                        $this->add_message($new_message);

                        F('longhu',$robot_t+rand(-3,3));
                    }
                }

//                $this->add_message($new_message);
            }
            //获取当前和上期 数据
            $hundred_info = M('hundred')->where("type=1")->order("id desc")->limit(2)->select();
            //触发结算操作结算上一期 上一期未结算且有结果 当前未结算无结果
            if($hundred_info[1]['status'] == '2' && $hundred_info[1]['award_numbers'] != '0' && $hundred_info[0]['award_numbers'] == '0'){
                //结算
                //开奖结果
                $period_number = $hundred_info[1]['period_number'];
//                $result_code = M('hundred')->field("award_numbers")->where("period_number='$period_number'")->find();
                //本期得奖方法集
                $award_int = explode(',',$hundred_info[1]['award_int']);
                //转成数组 方便使用
                $res_code = explode(',',$hundred_info[1]['award_numbers']);
                //当前局所有竞猜
                $list = M('order')->where("number = '$period_number' and state = 1 and is_add = 0 and game='longhu'")->order("time ASC")->select();

                if($list){
                    $quzc_z=0;$quzc_x=0;//去占成的
                    foreach($list as $k=>$v){
                        $id = $list[$k]['id'];
                        $userid = $list[$k]['userid'];
                        //给上级返现 并添加记录(ok)
                        if($list[$k]['t_id'] and C('fenxiao_set') == 2){
                            M('user')->where("id = {$list[$k]['t_id']}")->setInc('yong', $list[$k]['del_points']*C('fenxiao')*0.01);
                            M('user')->where("id = {$list[$k]['t_id']}")->setInc('t_add', $list[$k]['del_points']*C('fenxiao')*0.01);
                            $fx_data = array(
                                'uid' => $userid,
                                't_uid' => $list[$k]['t_id'],
                                'orderid' => $id,
                                'push_money' => $list[$k]['del_points'],
                                'rate' => C('fenxiao')*0.01,
                                'money' => $list[$k]['del_points']*C('fenxiao')*0.01,
                                'time' => time()
                            );
                            M('push_money')->add($fx_data);
                        }
                        //结算1：判断是否中奖$award_int
                        $user_add_point=0;
                        if(in_array($v['jincai_zl'],$award_int)){
                            //结算2：不同中奖不同解决
                            echo'有中奖';
                            switch($v['jincai_zl']){
                                case '1'://庄
                                    $user_add_point += $v['del_points'] * C('longhu_z_point');
                                    break;
                                case '2'://闲
                                    $user_add_point += $v['del_points'] * C('longhu_x_point');
                                    break;
                                case '3'://和
                                    $user_add_point += $v['del_points'] * C('longhu_h_point');
                                    break;
                                default:
                            }
                            //记录吃码量（对冲（实） 不足吃码量的部分）
                            switch($v['jincai_zl']) {
                                case '1'://龙
                                    $quzc_z += $v['quzc_points'];
                                    break;
                                case '2'://虎
                                    $quzc_x += $v['quzc_points'];
                                    break;
                            }
                        }
                        //去占成龙虎对冲
                        if ($quzc_z>$quzc_x){
                            $quzc_zx='龙';
                            $quzc_dc=$quzc_z-$quzc_x;
                        }elseif($quzc_z<$quzc_x){
                            $quzc_zx='虎';
                            $quzc_dc=$quzc_x-$quzc_z;
                        }else{
                            $quzc_dc=0;
                        }
                        if ($quzc_dc>0){//计算吃码后的值 （吃码量的倍数  多的不计）
                            if ($quzc_dc>=C('chima')){
                                $vv=$quzc_dc%C('chima');
                                $vv=$quzc_zx.'/'.$vv;
                                M("hundred")->where(['id'=>$hundred_info[1]['id']])->save(['chima'=>$vv]);
                            }
                        }
                        //修改用户表以及订单表的相关数据
                        $order_id = $v['id'];
                        $user_id = $v['userid'];
                        //修改order和user 发放中奖金额
                        $this->add_points($order_id,$user_id,$user_add_point);
                        $this->send_msg('pointsadd',$user_add_point,$user_id);
                        /*
                        //结算 根据上期开奖结果
                        //用户竞猜号 约定为 json 如 {'庄':100}
                        $odd_number_info = json_decode($v['jincai'],true);
                        $odd_numer = array_keys($odd_number_info);
                        //获取中奖号 并计算
                        $user_add_point = 0;
                        for($i=0;$i<count($odd_numer);$i++){
                            if(in_array($odd_numer[$i],$res_code)){
                                if($odd_numer[$i] == '龙'){
                                    $user_add_point += $odd_number_info[$odd_numer[$i]] * C('longhu_z_point');
                                }else if($odd_numer[$i] == '虎'){
                                    $user_add_point += $odd_number_info[$odd_numer[$i]] * C('longhu_x_point');
                                }else if($odd_numer[$i] == '和'){
                                    $user_add_point += $odd_number_info[$odd_numer[$i]] * C('longhu_h_point');
                                }
                            }else{
                                if(in_array('和',$res_code)){
                                    if($odd_numer[$i] == '龙'){
                                        $user_add_point += $odd_number_info[$odd_numer[$i]];
                                    }else if($odd_numer[$i] == '虎'){
                                        $user_add_point += $odd_number_info[$odd_numer[$i]];
                                    }
                                }
                            }
                        }
                        //修改用户表以及订单表的相关数据
                        $order_id = $v['id'];
                        $user_id = $v['userid'];
                        //修改order和user 发放中奖金额
                        $this->add_points($order_id,$user_id,$user_add_point);
                        $this->send_msg('pointsadd',$user_add_point,$user_id);*/


                    }

                    //推送实时变更的筹码  （实时码量）
                    $zhuang=0;//庄总计
                    $xian=0;//闲总计
                    foreach ($list as $k=>$v){
                        $xiazhu=json_decode($v['jincai'],true);
                        $xiazhu_class=array_keys($xiazhu)[0];
                        $xiazhu_val=array_values($xiazhu)[0];
                        if ('龙'==$xiazhu_class){
                            $zhuang+=$xiazhu_val;
                        }else if('虎'==$xiazhu_class){
                            $xian+=$xiazhu_val;
                        }
                    }
                    $zx=$zhuang-$xian;//龙虎对冲
//                    $bet_points=0;
                    $res_code = explode(',',$hundred_info[1]['award_numbers']);
                    $bet_points =$zx;//增减码量
                    if ('龙'==$res_code[0]){//开庄
//                        $bet_points*=1;//庄+
                        if ($zx>0) {//庄多
                            $bet_points = $zx * C('longhu_z_point') - $zx;
                        }
                    }else if ('虎'==$res_code[0]){//开闲
                        if ($zx>0) {//庄多
                            $bet_points = $zx*-1;
                        }else{
                            $bet_points=$zx * (C('longhu_x_point')-1)*-1;
                        }
                    }else{
                        $bet_points=0;
                    }
                    $bet_points=(int)$bet_points;
                    $conf = M("hundred_config")->field("id,has_points")->order("id desc")->find();
                    $conf_id = $conf['id'];
                    M("hundred_config")->where("id='$conf_id'")->setInc("has_points",$bet_points);
                }

            }
        });

        //系统公告(ready)
        \Workerman\Lib\Timer::add(1000, function(){
            $new_message = array(
                'type' => 'system',
                'code' => '200',
                'head_img_url'=>'/Uploads/'.kefuurl(),
                'from_client_name' => '客服',
                'content'=>'由于各地网络情况不同，开奖视频存在延迟，不会影响最终结果',
                'time'=>date('H:i:s')
            );
            foreach ($this->worker->connections as $conn) {
                $conn -> send(json_encode($new_message));
            }

        });

    }

    /*
     * 客户端连接时
     *
     * */
    public function onConnect($connection){
        $connection->onWebSocketConnect = function($connection , $http_header)
        {

        };
    }

    /**
     * onMessage
     * @access public
     * 转发客户端消息
     * @param  void
     * @param  void
     * @return void
     */
    public function onMessage($connection, $data) {
        $user = session('user');
        // 客户端传递的是json数据
        $message_data = json_decode($data, true);
        if (!$message_data) {
            return;
        }

        // 1:表示执行登陆操作 2:表示执行说话操作 3:表示执行退出操作
        // 根据类型执行不同的业务
        switch($message_data['type']){
            // 客户端回应服务端的心跳
            case 'pong' :
                // $connection -> send("success");
                break;
            case 'login' :
                // 把昵称放到session中
                $client_name = htmlspecialchars($message_data['client_name']);

                /* 保存uid到connection的映射，这样可以方便的通过uid查找connection，
                * 实现针对特定uid推送数据
                */
                $connection->uid = $message_data['client_id'];
                $this->worker->uidConnections[$connection->uid] = $connection;

                //session($connection->uid,$client_name);

                $new_message = array(
                    'type' => 'admin',
                    'code' => '200',
                    'head_img_url'=>'/Uploads/'.kefuurl(),
                    'from_client_name' => 'GM管理员',
                    'content' => C('welcome'),
                    'time' => date('H:i:s')
                );
                $connection -> send(json_encode($new_message));
                break;
            case 'say' :
                //type   say
                //number 期号
                //game   hundred
                //content 竞猜的参数
                $userid = $connection->uid;
                /*是否竞猜时间*/
                if(C('longhu_is_open') == '0'){
                    $time_error_message = array(
                        'uid'  => $connection->uid,
                        'type' => 'say',
                        'code' => '400',
                        'head_img_url'=>$message_data['headimgurl'],
                        'from_client_name' => $message_data['client_name'],
                        'content' => $message_data['content'],
                        'time' => date('H:i:s')
                    );

                    $connection -> send(json_encode($time_error_message));
                    $time_error_message['type'] = 'say_error';
                    $this->add_message($time_error_message);/*添加信息*/
                    $time_message = array(
                        'uid'  => $connection->uid,
                        'type' => 'admin',
                        'code' => '400',
                        'head_img_url'=>'/Uploads/'.kefuurl(),
                        'from_client_name' => 'GM管理员',
                        'content' => $message_data['content'].'非竞猜时间，竞猜失败',
                        'time' => date('H:i:s')
                    );
                    // $msg_data = array(
                    // 	'code' => '402',
                    // 	'msg'  => '非竞猜时间，竞猜失败',
                    // 	'content' => $time_message
                    // );
                    $connection -> send(json_encode($time_message));
                    $time_message['type'] = 'error';
                    $this->add_message($time_message);/*添加信息*/
                }
                else{
                    //检查投注时间 和 当前期数
                    $time = time();
                    $where=['open_time'=>['LT',$time],'type'=>'1',];//$where = "open_time < '{$time}' and type='1'";
                    $now = M('hundred')->where($where)->order("id desc")->limit("1")->select();
                    if($now[0]['status'] == '1'){
                        /*检测格式和金额*/
                        $money_data = $message_data['content'];

                        $sh=array_keys($money_data);
//                        $cx='撤庄 CZ 撤闲 CX 撤和 CH 撤对子 CDZ 撤庄对 CZD 撤闲对 CXD 撤三宝 CSB';//撤销命令
                        $qc=array('撤','C','全撤','QC',);
                        $cx=array('撤龙','CL','撤虎','CHu','撤和','CH');

                        if (in_array($sh[0],$qc)){//撤注单系列-全撤
                            M()->startTrans();
                            try {
                                //删除该玩家本期所有的投注
                                $user_id = $userid;
                                $where_zq=['number'=>$now[0]['period_number'],
                                    'userid'=>$userid,
                                    'game'=>'longhu'];
                                $msg='全撤成功';
                                $del_points= M('order')->where($where_zq)->sum('del_points');
                                if (0==$del_points){$msg='无可撤注单';}else{
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();
                                    M()->commit();
                                }
                                $new_message2 = array(
                                    'uid'  => $connection->uid,
                                    'type' => 'admin',
                                    'code' => '200',
                                    'head_img_url'=>'/Uploads/'.kefuurl(),
                                    'from_client_name' => 'GM管理员',
                                    'content' =>  $msg,
                                    'time' => date('H:i:s')
                                );
                                $connection -> send(json_encode($new_message2));
                            } catch (Exception $e) {
                                M()->rollback();
                            }
                            return;
                        }
                        else if(in_array($sh[0],$cx)){//撤注单系列-单撤
                            echo '单撤';
                            $where_zq=['number'=>$now[0]['period_number'],
                                'userid'=>$userid,
                                'game'=>'longhu'];
                            $msg=$sh[0];
                            if ('撤龙'==$sh[0]||'CL'==$sh[0]){
                                $msg='撤龙';
                                $where_zq['jincai_zl']=1;
                            }elseif('撤虎'==$sh[0]||'CHu'==$sh[0]){
                                $msg='撤虎';
                                $where_zq['jincai_zl']=2;
                            }elseif('撤和'==$sh[0]||'CH'==$sh[0]){
                                $msg='撤和';
                                $where_zq['jincai_zl']=3;
                            }
                            M()->startTrans();
                            try {
                                //删除该玩家本期所有的投注
                                $user_id = $userid;

                                $del_points= M('order')->where($where_zq)->sum('del_points');
                                if (0==$del_points){$msg=$msg.'失败，没有下注';}else{
                                    $msg= $msg.'成功';
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();
                                    M()->commit();
                                }

                                //GM管理员发给个人的竞猜通知
                                $new_message2 = array(
                                    'uid'  => $connection->uid,
                                    'type' => 'admin',
                                    'code' => '200',
                                    'head_img_url'=>'/Uploads/'.kefuurl(),
                                    'from_client_name' => 'GM管理员',
                                    'content' =>  $msg,
                                    'time' => date('H:i:s')
                                );
                                $connection -> send(json_encode($new_message2));
                            } catch (Exception $e) {
                                M()->rollback();
                            }
                            return;
                        }

                        $user_info = M("user")->field("id,points,nickname,username,t_id")->where("id='$userid' and status=1")->find();
                        if (stristr($sh[0],'梭哈')){//梭哈系列

                            //查询余额
                            $user_points=(int)$user_info['points'];
                            $sh_xilie=array('梭哈龙','梭哈虎','梭哈和');//梭哈系列
//                            $isin = array_search($sh_xilie,$sh[0]);//在数组中搜索键值 $a，并返回它的键名：
                            $xiazhu= xiazhu_daima($sh[0]);
                            $xiazhu2=jingcai_zi_lh_fanyi($xiazhu);
                            $money_data=[$xiazhu2=>$user_points];

                        }

                        $res = $this->checkHundredMoney($userid,$money_data,$now[0]['period_number']);

                        if($res['code']== '0'){
                            $all_money = array_sum($money_data);
                            $message=[
                                'uid'=>$connection->uid,
                                'type' => 'admin',
                                'head_img_url'=>'/Uploads/'.kefuurl(),
                                'from_client_name' => 'GM管理员',
                                'code' => '400',
//								'head_img_url'=> $message_data['headimgurl'],
//								'from_client_name' => $message_data['client_name'],
                                'content' => $all_money,
                                'time' => date('H:i:s')
                            ];
                            $connection -> send(json_encode($message));
                            $error_message = array(
                                'uid'=>$connection->uid,
                                'type' => 'admin',
                                'head_img_url'=>'/Uploads/'.kefuurl(),
                                'from_client_name' => 'GM管理员',
                                'code' => '400',
//								'head_img_url'=> $message_data['headimgurl'],
//								'from_client_name' => $message_data['client_name'],
                                'content' => $res['content'],
                                'time' => date('H:i:s')
                            );
                            // $msg_data = array(
                            // 	'code' => '401',
                            // 	'msg'  => $res['content'],
                            // 	'content' => $error_message
                            // );
                            $connection -> send(json_encode($error_message));
                            $error_message['type'] = 'say_error';
                            $this->add_message($error_message);/*添加信息*/
                        }
                        else if($res['code'] == '1'){
                            $map['userid'] = $userid;
                            $map['state'] = 1;
                            $map['is_add'] = 0;
                            $map['time'] = time();
                            $map['number'] = $now[0]['period_number'];
                            $map['jincai_zl'] =$res['jincai_zl'];
                            $map['jincai'] = json_encode($message_data['content'],JSON_UNESCAPED_UNICODE);
                            $map['del_points'] = $res['all_money'];
                            $map['balance'] = $res['points']-$res['all_money'];
                            $map['nickname'] = $res['nickname'];
                            $map['username'] = $res['username'];
                            $map['game'] = 'longhu';
                            $map['t_id'] = $res['t_id'];
                            $quzc_points=$map['del_points'];
                            if ($map['jincai_zl']==1||$map['jincai_zl']==2){//龙/虎去占成
                                $user=M('user')->find($connection->uid);
                                $t_id=$user['t_id'];
                                if ($t_id>0){//查看代理占成
                                    $t_user=M('user')->where(['id'=>$t_id,'is_agent'=>1])->find();
                                    if ($t_user&&$t_user['zhancheng']>0){
                                        $quzc_points=$map['del_points']*(1-($t_user['zhancheng']/100));
                                    }
                                }
                            }
                            $map['quzc_points']=$quzc_points;//去占成后的投注
                            /*添加竞猜*/
                            if(!$res['is_robot']) {
                                M()->startTrans();
                                try {
                                    //删除之前的投注
                                    //1.找到该用户本期之前的相同投注
                                    $user_id = $userid;
                                    $where_zq=['number'=>$map['number'],
                                        'jincai_zl'=>$map['jincai_zl'],
                                        'game'=>$map['game']];
                                    $del_points= M('order')->where($where_zq)->sum('del_points');
                                    M('user')->where("id = $user_id")->setInc('points',$del_points);
                                    M('order')->where($where_zq)->delete();

                                    /*减分*//*添加竞猜*/
                                    M('order')->add($map);
                                    M('user')->where("id = $userid")->setDec('points', $map['del_points']);
                                    M()->commit();
                                } catch (Exception $e) {
                                    M()->rollback();
                                }
                                //变更的筹码
//								$conf = M("hundred_config")->field("id,has_points")->order("id desc")->find();
//								$conf_id = $conf['id'];
//								M("hundred_config")->where("id='$conf_id'")->setDec("has_points", $map['del_points']);
//								$has_points = $conf['has_points']-$map['del_points'];
//								$this->send_fen($content=array('has_points'=>$has_points));
                            }
                            /*成功通知*/
                            $jincai_data = json_decode($map['jincai'],true);
                            $jincai_keys = array_keys($jincai_data);
//							$jincai = $jincai_str.':'.$jincai_num;
                            foreach($jincai_keys as $k=>$v){
                                $new_message2 = array(
                                    'uid'  => $connection->uid,
                                    'type' => 'admin',
                                    'code' => '200',
                                    'head_img_url'=>'/Uploads/'.kefuurl(),
                                    'from_client_name' => 'GM管理员',
                                    'content' =>  '「'.$v.'/'.$jincai_data[$v].'」'.',竞猜成功',
                                    'time' => date('H:i:s')
                                );
                                $connection -> send(json_encode($new_message2));
//								$this->add_message($new_message2);/*添加信息*/
                                $new_message3 = array(
                                    'type' => 'say',
                                    'head_img_url'=> $message_data['headimgurl'],
                                    'from_client_name' => $message_data['client_name'],
                                    'content' => $v.'/'.$jincai_data[$v],
                                    'time' => date('H:i:s'),
                                    'uid' => $map['t_id'],
                                );
                                $this->add_message($new_message3);/*添加信息*/
                                $new_message4 = array(
                                    'type' => 'say',
                                    'head_img_url'=> $message_data['headimgurl'],
                                    'from_client_name' => $message_data['client_name'],
                                    'content' => $v.'/'.$jincai_data[$v],
                                    'time' => date('H:i:s')
                                );
                                // //向全体发送消息
                                // foreach ($this->worker->connections as $conn) {
                                // 	$conn -> send(json_encode($new_message4));
                                // }
                                $point = 0-$jincai_data[$v];
                                $this->send_msg('pointsadd',$point,$userid);
                                //查询上级代理id
                                $agent_info = M("user")->field("t_id")->where("id='$userid'")->find();
                                if($agent_info['t_id'] == '0'){
                                    $agent_id = '0';
                                }else{
                                    $agent_id = $agent_info['t_id'];
                                }
                                // //向全体发送消息
                                 foreach ($this->worker->connections as $conn) {
                                 	$conn -> send(json_encode($new_message4));
                                 }
                                 //向同代理发送
//                                $next_users = M("user")->field("id")->where("t_id='$agent_id'")->select();
//                                foreach ($next_users as $k=>$v){
//                                    $userid = $next_users[$k]['id'];
//                                    if(isset($this->worker->uidConnections[$userid])){
//                                        $connection = $this->worker->uidConnections[$userid];
//                                        $connection->send(json_encode($new_message4));
//                                    }
//                                }
                            }
                        }
                    }
                    else{
                        $msg_data = array(
                            'uid'  => $connection->uid,
                            'type' => 'admin',
                            'code' => '400',
                            'head_img_url'=>'/Uploads/'.kefuurl(),
                            'from_client_name' => 'GM管理员',
                            'msg'  => '不在投注时间内',
                            'content' => '不在投注时间内',
                            'time' => date('H:i:s'),
                            'status' => $now[0]['status'],
                        );
                        $connection -> send(json_encode($msg_data));
                        $msg_data_say = array(
                            'uid'=>$connection->uid,
                            'type' => 'say',
                            'status' => $user['is_under'],
                            'head_img_url'=> $message_data['headimgurl'],
                            'from_client_name' => $message_data['client_name'],
                            'content' => $map['jincai'],
                            'time' => date('H:i:s')
                        );
                        $connection -> send(json_encode($msg_data_say));
                    }
                }
                break;

            case 'admin':
                $new_message = array(
                    'type' => 'admin',
                    'code' => '200',
                    'head_img_url'=>'/Uploads/'.kefuurl(),
                    'from_client_name' => 'GM管理员',
                    'content' => C('welcome'),
                    'time' => date('H:i:s')
                );
                break;
        }
    }


    public function robot_message(){
        $xiazhu=['龙','虎','和'];

        $jiner=[10,30];//最小，最大,
//        range(10,3000,10);//最小，最大,间隔

        $data=$xiazhu[array_rand($xiazhu)].'/'.rand($jiner[0],$jiner[1]*10);
        return $data;
    }

    public function robot(){
        $count = M('robot')->count();
        $rand = mt_rand(0,$count-1); //产生随机数。
        $limit = $rand.','.'1';
        $data = M('robot')->limit($limit)->select();
        return $data;
    }

    /**
     * onClose
     * 关闭连接
     * @access public
     * @param  void
     * @return void
     */
    public function onClose($connection) {
        $user = session($connection->id);
        foreach ($this->worker->uidConnections as $con) {
            if (!empty($user)) {
                $new_message = array(
                    'type' => 'logout',
                    'from_client_name' => $user,
                    'time' => date('H:i:s')
                );
                $con -> send(json_encode($new_message));
            }
        }

        if(isset($connection->uid)){
            // 连接断开时删除映射
            unset($this->worker->uidConnections[$connection->uid]);
        }
    }


    /*存竞猜记录和信息*/
    protected function add_order($mew_message){
        $res = M('order')->add($mew_message);
        return $res;
    }

    protected function add_message($new_message){

        if (!empty($new_message)) {
            $new_message['game'] = 'longhu';
            $res = M('message')->add($new_message);
            return $res;
        }
    }


    /*
     * 竞猜成功  加分
     * */
    public function add_points($order_id,$userid,$points){
        M()->startTrans();
        try {
            M('user')->where("id = $userid")->setInc('points',$points);
            $user_points= $this->user_points($userid);
            M('order')->where("id = $order_id")->setField(array('is_add'=>'1','add_points'=>$points,'balance'=>$user_points));
            M()->commit();
        } catch (Exception $e) {
            M()->rollback();
        }
    }

    /*竞猜成功通知
     * */
    public function send_msg($type,$points,$userid){
        $message_points = array(
            'type' => $type,
            'points'=>	$points,
            'userid' =>$userid,
            'time'=>date('H:i:s')
        );
        if(isset($this->worker->uidConnections[$userid])){
            $connection = $this->worker->uidConnections[$userid];
            $connection->send(json_encode($message_points));
        }
    }

    /*核对投注钱数
     * userid 用户id
     * moneyData 投注金额的数组
     * */
    public function checkHundredMoney($userid,$money_data,$number){
        $res = array();
        //查询该用户的金额是否能够投注
        $user_info = M("user")->field("id,points,nickname,username,t_id")->where("id='$userid' and status=1")->find();
        $all_money = array_sum($money_data); //投注的总钱数
        //查询之前的投注总额
        $before = M("order")->field("del_points,jincai")->where("userid='$userid' and is_add=0 and number='$number'")->select();

        if($all_money > C('longhu_min_money') && $all_money < C('longhu_max_money')){
            if($all_money <= $user_info['points']){

                $zong_del_points = M("order")->where("userid='$userid' and is_add=0 and number='$number'")->sum('del_points');

                $zong = $zong_del_points;

                $bet = json_decode($money_data,true);
                $bet_key = array_keys($money_data);
                if($bet_key[0] == '和'){
                    $bet_money = $all_money;
                    if($bet_money > C('longhu_h_money')){
                        $res['code'] = "0";
                        $res['content'] = "和超出限额";
                        return $res;
                    }
                }
                else if($bet_key[0] == '龙' ){
                    $bet_money = $all_money;
                    if($bet_money > C('longhu_z_money')){
                        $res['code'] = "0";
                        $res['content'] = "龙超出限额".C('longhu_z_money');
                        return $res;
                    }
                }
                else if($bet_key[0] == '虎'){
                    $bet_money = $all_money;
                    if($bet_money > C('longhu_x_money')){
                        $res['code'] = "0";
                        $res['content'] = "虎超出限额". C('longhu_x_money');
                        return $res;
                    }
                }
                else{
                    $res['code'] = "0";
                    $res['content'] = "不支持该投注";
                    return $res;
                }
                $bet_money = $zong + $all_money;
                if($bet_money > C('longhu_max_money')){
                    $res['code'] = "0";
                    $res['content'] = "投注超出最高限额";
                    return $res;
                }
                $xiazhu= xiazhu_daima($bet_key[0]);
                $res['code'] = "1";
                $res['all_money'] = $all_money;
                $res['jincai_zl']=$xiazhu;
                $res['nickname'] = $user_info['nickname'];
                $res['username'] = $user_info['username'];
                $res['t_id'] = $user_info['t_id'];
                $res['points'] = $user_info['points'];
                $res['is_robot'] = $user_info['is_robot'];
            }else{
                $res['code'] = "0";
                $res['content'] = "账户金额不足";
            }
        }else if ($all_money<=C('longhu_min_money')){
            $res['code'] = "0";
            $res['content'] = "低于规则投注限额";
        }else if ($all_money>=C('longhu_max_money')){
            $res['code'] = "0";
            $res['content'] = "投注超出最高限额";
        }
        return $res;
    }

    protected function send_fen($content){
        // 指明给谁推送，为空表示向所有在线用户推送
        $to_uid = 0;
        // 推送的url地址，上线时改成自己的服务器地址
        $push_api_url = "http://localhost:12225/";
        $post_data = array(
            "type" => "publish",
            "content" => json_encode($content),
            "to" => $to_uid,
        );
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }
	
	
	
}
?>